namespace RBAC.Read.Api.Application.Handler.BomHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.BomManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Read.Api.Application.Command.BomCommand;
    using RBAC.Read.Api.Application.Dto.Bom;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// 按 BomId 获取 BomItem 树形结构 处理器
    /// </summary>
    public class GetBomItemTreeByBomIdHandler : IRequestHandler<GetBomItemTreeByBomIdCommand, APIResult<List<BomItemTreeDto>>>
    {
        private readonly IBaseRepository<BomItem> repository;
        private readonly ILogger<GetBomItemTreeByBomIdHandler> logger;

        public GetBomItemTreeByBomIdHandler(IBaseRepository<BomItem> repository, ILogger<GetBomItemTreeByBomIdHandler> logger)
        {
            this.repository = repository;
            this.logger = logger;
        }

        public Task<APIResult<List<BomItemTreeDto>>> Handle(GetBomItemTreeByBomIdCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<BomItemTreeDto>>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (request.BomId <= 0)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "参数无效：BomId 必须大于 0";
                    result.Data = new List<BomItemTreeDto>();
                    return Task.FromResult(result);
                }

                // 查询指定BOM的所有明细
                var items = repository.GetAll("BomId = @BomId AND IsDeleted = 0", new { request.BomId })
                    .OrderBy(x => x.Position ?? int.MaxValue)
                    .ThenBy(x => x.Id)
                    .ToList();

                // 构建节点映射
                var nodeMap = items.ToDictionary(
                    x => x.Id,
                    x => new BomItemTreeDto
                    {
                        Id = x.Id,
                        BomId = x.BomId,
                        BomName = x.BomName,
                        ParentId = x.ParentId,
                        MaterialId = x.MaterialId,
                        MaterialName = x.MaterialName,
                        Qty = x.Qty,
                        Position = x.Position,
                        Children = new List<BomItemTreeDto>()
                    });

                // 组装父子关系
                var roots = new List<BomItemTreeDto>();
                foreach (var node in nodeMap.Values)
                {
                    if (node.ParentId.HasValue && nodeMap.TryGetValue(node.ParentId.Value, out var parent))
                    {
                        parent.Children.Add(node);
                    }
                    else
                    {
                        roots.Add(node);
                    }
                }

                result.Code = APIEnums.Success;
                result.Msg = "获取BOM明细树成功";
                result.Data = roots;
            }
            catch (OperationCanceledException)
            {
                logger.LogWarning("获取BOM明细树被取消");
                result.Code = APIEnums.Error;
                result.Msg = "请求已取消";
                result.Data = new List<BomItemTreeDto>();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取BOM明细树失败: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "获取BOM明细树失败";
                result.Data = new List<BomItemTreeDto>();
            }

            return Task.FromResult(result);
        }
    }
}
